package com.kl.chat;

import com.kl.decodeandencode.MyMessage;
import com.kl.decodeandencode.MyMessageDecode;
import com.kl.decodeandencode.MyMessageEncode;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class NettyClient {
    //static Bootstrap bootstrap;
    public static void main(String[] args) throws Exception {
        //客户端需要一个事件循环组
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            //创建客户端启动对象
            //注意客户端使用的不是 ServerBootstrap 而是 Bootstrap
            Bootstrap bootstrap = new Bootstrap();
            //设置相关参数
            bootstrap.group(group) //设置线程组
                    .channel(NioSocketChannel.class) // 使用 NioSocketChannel 作为客户端的通道实现
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel) {
                            ChannelPipeline pipeline = channel.pipeline();
                            //加解码器和编码器
                            pipeline.addLast(new MyMessageEncode());
                            pipeline.addLast(new MyMessageDecode());
                            //加入处理器
                            pipeline.addLast(new NettyClientHandler());
                        }
                    });
            System.out.println("netty client start");
            //启动客户端去连接服务器端
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 9000).sync();
            //ChannelFuture channelFuture = connect();
            Channel channel = channelFuture.channel();
            System.out.println("=====" + channel.localAddress() + "=====");
            Scanner scanner = new Scanner(System.in);
            // 测试是否会粘包拆包
            for (int i = 0; i <= 10; i++) {
                String str = "你好呀滴滴答答坤sir!";
                byte[] strBytes = str.getBytes(StandardCharsets.UTF_8);
                MyMessage myMessage = new MyMessage(strBytes.length, strBytes);
                channel.writeAndFlush(myMessage);
            }
            // 真实要通信的数据
//            while (scanner.hasNextLine()) {
//                byte[] contents = scanner.nextLine().getBytes(StandardCharsets.UTF_8);
//                // 通过channel将消息发送到服务器，指定消息字节长度和具体内容
//                channel.writeAndFlush(new MyMessage(contents.length, contents));
//            }
        } finally {
            group.shutdownGracefully();
        }
    }

    /*public static ChannelFuture connect() throws InterruptedException {
        ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 9000);
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    future.channel().eventLoop().schedule(() -> {
                        System.err.println("重连服务器...");
                        try {
                            connect();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }, 3000, TimeUnit.MILLISECONDS);
                } else {
                    System.out.println("服务器连接成功");
                }
            }
        });
        channelFuture.channel().closeFuture().sync();
        return channelFuture;
    }*/
}
